import 'dart:collection';

import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_inappwebview/flutter_inappwebview.dart';
import 'package:hxdj/common/components/my_scaffold.dart';

class MyWebviewPage extends StatefulWidget {
  // 路由地址
  static String routeName = "/MyWebviewPage";

  final String url;
  final String title;

  const MyWebviewPage({super.key, required this.url, required this.title});

  @override
  State<MyWebviewPage> createState() => _MyWebviewPageState();
}

class _MyWebviewPageState extends State<MyWebviewPage> {
  final GlobalKey webViewKey = GlobalKey();

  InAppWebViewController? webViewController;
  InAppWebViewSettings settings = InAppWebViewSettings(
      isInspectable: kDebugMode,
      mediaPlaybackRequiresUserGesture: false,
      allowsInlineMediaPlayback: true,
      iframeAllow: "camera; microphone",
      iframeAllowFullscreen: true);

  PullToRefreshController? pullToRefreshController;

  late ContextMenu contextMenu;
  String url = "";
  double progress = 0;
  String _webTitle = "";

  @override
  void initState() {
    super.initState();

    contextMenu = ContextMenu(
        menuItems: [
          ContextMenuItem(
              id: 1,
              title: "Special",
              action: () async {
                print("Menu item Special clicked!");
                print(await webViewController?.getSelectedText());
                await webViewController?.clearFocus();
              })
        ],
        settings: ContextMenuSettings(hideDefaultSystemContextMenuItems: false),
        onCreateContextMenu: (hitTestResult) async {
          debugPrint("onCreateContextMenu");
          debugPrint(hitTestResult.extra);
          debugPrint(await webViewController?.getSelectedText());
        },
        onHideContextMenu: () {
          debugPrint("onHideContextMenu");
        },
        onContextMenuActionItemClicked: (contextMenuItemClicked) async {
          var id = contextMenuItemClicked.id;
          debugPrint("onContextMenuActionItemClicked: $id ${contextMenuItemClicked.title}");
        });

    pullToRefreshController = kIsWeb || ![TargetPlatform.iOS, TargetPlatform.android].contains(defaultTargetPlatform)
        ? null
        : PullToRefreshController(
            settings: PullToRefreshSettings(
              color: Colors.blue,
            ),
            onRefresh: () async {
              if (defaultTargetPlatform == TargetPlatform.android) {
                webViewController?.reload();
              } else if (defaultTargetPlatform == TargetPlatform.iOS || defaultTargetPlatform == TargetPlatform.macOS) {
                webViewController?.loadUrl(urlRequest: URLRequest(url: await webViewController?.getUrl()));
              }
            },
          );
  }

  @override
  Widget build(BuildContext context) {
    return MyScaffold(
      title: _webTitle,
      body: SafeArea(
          child: Column(children: <Widget>[
        Expanded(
          child: Stack(
            children: [
              InAppWebView(
                key: webViewKey,
                initialUrlRequest: URLRequest(url: WebUri(widget.url)),
                // initialUrlRequest:
                // URLRequest(url: WebUri(Uri.base.toString().replaceFirst("/#/", "/") + 'page.html')),
                // initialFile: "assets/index.html",
                initialUserScripts: UnmodifiableListView<UserScript>([]),
                initialSettings: settings,
                contextMenu: contextMenu,
                pullToRefreshController: pullToRefreshController,
                onWebViewCreated: (controller) async {
                  webViewController = controller;
                },
                onLoadStart: (controller, url) async {},
                onPermissionRequest: (controller, request) async {
                  return PermissionResponse(resources: request.resources, action: PermissionResponseAction.GRANT);
                },
                shouldOverrideUrlLoading: (controller, navigationAction) async {
                  // var uri = navigationAction.request.url!;

                  // if (![
                  //   "http",
                  //   "https",
                  //   "file",
                  //   "chrome",
                  //   "data",
                  //   "javascript",
                  //   "about"
                  // ].contains(uri.scheme)) {
                  //   if (await canLaunchUrl(uri)) {
                  //     // Launch the App
                  //     await launchUrl(
                  //       uri,
                  //     );
                  //     // and cancel the request
                  //     return NavigationActionPolicy.CANCEL;
                  //   }
                  // }

                  return NavigationActionPolicy.ALLOW;
                },
                onLoadStop: (controller, url) async {
                  pullToRefreshController?.endRefreshing();
                },
                onReceivedError: (controller, request, error) {
                  pullToRefreshController?.endRefreshing();
                },
                onProgressChanged: (controller, progress) {
                  if (progress == 100) {
                    pullToRefreshController?.endRefreshing();
                  }
                  setState(() {
                    this.progress = progress / 100;
                  });
                },
                onUpdateVisitedHistory: (controller, url, isReload) {
                  setState(() {});
                },
                onConsoleMessage: (controller, consoleMessage) {
                  debugPrint(consoleMessage.message);
                },
                onTitleChanged: (InAppWebViewController controller, String? title) {
                  setState(() {
                    _webTitle = title ?? "";
                  });
                },
              ),
              progress < 1.0 ? LinearProgressIndicator(value: progress) : Container(),
            ],
          ),
        ),
        // ButtonBar(
        //   alignment: MainAxisAlignment.center,
        //   children: <Widget>[
        //     ElevatedButton(
        //       child: const Icon(Icons.arrow_back),
        //       onPressed: () {
        //         webViewController?.goBack();
        //       },
        //     ),
        //     ElevatedButton(
        //       child: const Icon(Icons.arrow_forward),
        //       onPressed: () {
        //         webViewController?.goForward();
        //       },
        //     ),
        //     ElevatedButton(
        //       child: const Icon(Icons.refresh),
        //       onPressed: () {
        //         webViewController?.reload();
        //       },
        //     ),
        //   ],
        // ),
      ])),
    );
  }
}



// import 'package:flutter/material.dart';
// import 'package:flutter/services.dart';
// import 'package:flutter_inappwebview/flutter_inappwebview.dart';
// import 'dart:async';

// /// App内部Web浏览器页面
// class BrowserPage extends StatefulWidget {
//   const BrowserPage(this.url, {Key? key}) : super(key: key);

//   final String url;

//   @override
//   State createState() => _BrowserPageState();
// }



// class _BrowserPageState extends State<BrowserPage> {
//   InAppWebViewController? _webViewController;
//   String? _webTitle;
//   double _progress = 0;
//   bool isCanGoBack = false;
//   bool isCanForward = false;

//  

//   @override
//   Widget build(BuildContext context) {
//     return WillPopScope(
//         onWillPop: () {
//           Future<bool> canGoBack = _webViewController!.canGoBack();
//           return canGoBack.then((isCanGoBack) {
//             if (isCanGoBack) {
//               _webViewController!.goBack();
//               return false;
//             } else {
//               return true;
//             }
//           });
//         },
//         child: Scaffold(
//           resizeToAvoidBottomInset: false,
//           appBar: AppBar(
//             leading: Row(
//               children: [
//                 isCanGoBack
//                     ? IconButton(
//                         onPressed: () {
//                           _webViewController?.goBack();
//                         },
//                         icon: const Icon(Icons.arrow_back))
//                     : IconButton(
//                         icon: const Icon(Icons.close),
//                         onPressed: () {
//                           SystemNavigator.pop();
//                         })
//               ],
//             ),
//             title: Text(_webTitle ?? "FlutterWebView"),
//           ),
//           body: Column(
//             children: [
//               Expanded(
//                   child: Stack(
//                 children: [
//                   InAppWebView(
//                     initialUrlRequest: URLRequest(url: Uri.parse(widget.url)),
//                     initialOptions: options,
//                     onWebViewCreated: (InAppWebViewController controller) {
//                       _webViewController = controller;
//                     },
//                     onTitleChanged:
//                         (InAppWebViewController controller, String? title) {
//                       setState(() {
//                         _webTitle = title ?? "";
//                       });
//                     },
//                     onLoadStop: (InAppWebViewController controller, Uri? url) {
//                       //页面加载完毕，显示隐藏AppBar的返回键
//                       controller.canGoBack().then((canGoBack) => {
//                             setState(() {
//                               isCanGoBack = canGoBack;
//                             })
//                           });
//                       controller.canGoForward().then((canForward) => {
//                             setState(() {
//                               isCanForward = canForward;
//                             })
//                           });
//                     },
//                     onProgressChanged:
//                         (InAppWebViewController controller, int progress) {
//                       //进度从0 ~ 100
//                       setState(() {
//                         _progress = progress / 100.0;
//                       });
//                     },
//                   ),
//                   _createProgressBar(_progress, context)
//                 ],
//               ))
//             ],
//           ),
//         ));
//   }
// }



